package com.bear.atlassianmcp.jira.service;

import com.bear.atlassianmcp.jira.config.JiraProperties;
import com.bear.atlassianmcp.jira.exception.JiraIntegrationException;
import com.bear.atlassianmcp.jira.model.JiraIssue;
import com.bear.atlassianmcp.jira.model.JiraProject;
import com.bear.atlassianmcp.jira.model.JiraSearchResult;
import com.bear.atlassianmcp.jira.model.JiraUser;
import com.bear.atlassianmcp.jira.model.JiraAttachment;
import com.bear.atlassianmcp.jira.model.request.CreateIssueRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

import jakarta.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Jira API服务
 * 负责与Jira REST API的所有交互
 */
@Service
public class JiraService {

    private static final Logger logger = LoggerFactory.getLogger(JiraService.class);

    private final RestTemplate restTemplate;
    private final JiraAuthService authService;
    private final JiraProperties jiraProperties;
    private final ObjectMapper objectMapper;

    @Autowired
    public JiraService(@Qualifier("jiraRestTemplate") RestTemplate restTemplate,
                      JiraAuthService authService,
                      JiraProperties jiraProperties) {
        this.restTemplate = restTemplate;
        this.authService = authService;
        this.jiraProperties = jiraProperties;
        this.objectMapper = new ObjectMapper();
    }

    /*@PostConstruct
    public void init() {
        // 验证认证配置
        authService.validateAuthConfiguration();
        logger.info("JiraService initialized successfully for base URL: {}", 
                   jiraProperties.getBaseUrl());
    }*/

    /**
     * 获取Issue详情（支持ToolContext）
     *
     * @param issueKey Issue键值，如"PROJ-123"
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return JiraIssue对象
     */
    public JiraIssue getIssue(String issueKey, ToolContext toolContext) {
        logger.debug("Getting issue: {}", issueKey);

        String url = authService.getApiBaseUrl() + "/issue/" + issueKey;

        try {
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name());
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<JiraIssue> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, JiraIssue.class);

            JiraIssue issue = response.getBody();
            logger.info("Successfully retrieved issue: {}", issueKey);
            return issue;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Issue not found: " + issueKey);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to issue: " + issueKey);
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to get issue: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error getting issue: " + e.getMessage(), e);
        }
    }

    /**
     * 创建新Issue（支持ToolContext）
     *
     * @param request 创建Issue请求
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 创建的Issue信息
     */
    public JiraIssue createIssue(CreateIssueRequest request, ToolContext toolContext) {
        logger.debug("Creating issue in project: {}",
                    request.getFields().get("project"));

        String url = authService.getApiBaseUrl() + "/issue";

        try {
            String requestBody = objectMapper.writeValueAsString(request.build());
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name());
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<JiraIssue> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, JiraIssue.class);

            JiraIssue createdIssue = response.getBody();
            logger.info("Successfully created issue: {}", createdIssue.getKey());
            return createdIssue;

        } catch (JsonProcessingException e) {
            throw new JiraIntegrationException("Failed to serialize create issue request", e);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                throw JiraIntegrationException.apiCallFailed(
                    "Invalid issue data: " + e.getResponseBodyAsString(), 400);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to create issue");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to create issue: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error creating issue: " + e.getMessage(), e);
        }
    }

    /**
     * 更新Issue字段（支持ToolContext）
     *
     * @param issueKey Issue键值
     * @param field 字段名
     * @param value 新值
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 更新结果消息
     */
    public String updateIssue(String issueKey, String field, Object value, ToolContext toolContext) {
        logger.debug("Updating issue {} field: {} = {}", issueKey, field, value);

        String url = authService.getApiBaseUrl() + "/issue/" + issueKey;

        try {
            Map<String, Object> updateData = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            fields.put(field, value);
            updateData.put("fields", fields);

            String requestBody = objectMapper.writeValueAsString(updateData);
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.PUT.name());
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
            
            restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
            
            String message = String.format("Successfully updated issue %s: %s = %s", 
                                         issueKey, field, value);
            logger.info(message);
            return message;
            
        } catch (JsonProcessingException e) {
            throw new JiraIntegrationException("Failed to serialize update request", e);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Issue not found: " + issueKey);
            } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                throw JiraIntegrationException.apiCallFailed(
                    "Invalid update data: " + e.getResponseBodyAsString(), 400);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to update issue: " + issueKey);
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to update issue: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error updating issue: " + e.getMessage(), e);
        }
    }

    /**
     * 为Issue添加评论（支持ToolContext）
     *
     * @param issueKey Issue键值
     * @param comment 评论内容
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 评论结果消息
     */
    public String addComment(String issueKey, String comment, ToolContext toolContext) {
        logger.debug("Adding comment to issue: {}", issueKey);

        String url = authService.getApiBaseUrl() + "/issue/" + issueKey + "/comment";

        try {
            Map<String, Object> commentData = new HashMap<>();
            commentData.put("body", comment);

            String requestBody = objectMapper.writeValueAsString(commentData);
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name());
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            String message = String.format("Successfully added comment to issue %s", issueKey);
            logger.info(message);
            return message;

        } catch (JsonProcessingException e) {
            throw new JiraIntegrationException("Failed to serialize comment request", e);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Issue not found: " + issueKey);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to comment on issue: " + issueKey);
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to add comment: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error adding comment: " + e.getMessage(), e);
        }
    }

    /**
     * 搜索Issues（支持ToolContext）
     *
     * @param jql JQL查询语句
     * @param maxResults 最大结果数
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 搜索结果
     */
    public JiraSearchResult searchIssues(String jql, Integer maxResults, ToolContext toolContext) {
        logger.debug("Searching issues with JQL: {}", jql);

        String url = authService.getApiBaseUrl() + "/search";

        // 使用配置的默认值或传入的值
        int limit = maxResults != null ? maxResults : jiraProperties.getMaxResults();

        try {
            Map<String, Object> searchData = new HashMap<>();
            searchData.put("jql", jql);
            searchData.put("maxResults", limit);
            searchData.put("startAt", 0);

            String requestBody = objectMapper.writeValueAsString(searchData);
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name());
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<JiraSearchResult> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, JiraSearchResult.class);

            JiraSearchResult result = response.getBody();
            logger.info("Search completed: found {} issues", result.getTotal());
            return result;

        } catch (JsonProcessingException e) {
            throw new JiraIntegrationException("Failed to serialize search request", e);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                throw JiraIntegrationException.apiCallFailed(
                    "Invalid JQL query: " + e.getResponseBodyAsString(), 400);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to search issues: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error searching issues: " + e.getMessage(), e);
        }
    }

    /**
     * 获取所有项目列表（支持ToolContext）
     *
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 项目列表
     */
    public List<JiraProject> getProjects(ToolContext toolContext) {
        logger.debug("Getting all projects");

        String url = authService.getApiBaseUrl() + "/project";

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext,  url, "GET"));
            ResponseEntity<JiraProject[]> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, JiraProject[].class);

            List<JiraProject> projects = Arrays.asList(response.getBody());
            logger.info("Successfully retrieved {} projects", projects.size());
            return projects;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to projects");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to get projects: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error getting projects: " + e.getMessage(), e);
        }
    }

    /**
     * 获取指定项目详情（支持ToolContext）
     *
     * @param projectKey 项目键值
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 项目详情
     */
    public JiraProject getProject(String projectKey, ToolContext toolContext) {
        logger.debug("Getting project: {}", projectKey);

        String url = authService.getApiBaseUrl() + "/project/" + projectKey;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<JiraProject> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, JiraProject.class);

            JiraProject project = response.getBody();
            logger.info("Successfully retrieved project: {}", projectKey);
            return project;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Project not found: " + projectKey);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to project: " + projectKey);
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to get project: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error getting project: " + e.getMessage(), e);
        }
    }

    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     */
    public JiraUser getCurrentUser(ToolContext toolContext) {
        logger.debug("Getting current user info");

        String url = authService.getApiBaseUrl() + "/myself";

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<JiraUser> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, JiraUser.class);

            JiraUser user = response.getBody();
            logger.info("Successfully retrieved current user: {}", user.getDisplayName());
            return user;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to get current user: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error getting current user: " + e.getMessage(), e);
        }
    }

    /**
     * 测试Jira连接
     *
     * @return 连接测试结果消息
     */
    public String testConnection(ToolContext toolContext) {
        logger.debug("Testing Jira connection");

        try {
            JiraUser currentUser = getCurrentUser(toolContext);
            String message = String.format("Connection successful! Connected as: %s (%s)",
                                         currentUser.getDisplayName(), currentUser.getName());
            logger.info("Jira connection test successful");
            return message;

        } catch (Exception e) {
            logger.error("Jira connection test failed", e);
            throw new JiraIntegrationException("Connection test failed: " + e.getMessage(), e);
        }
    }

    /**
     * 获取当前用户分配的Issues（支持ToolContext）
     *
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 搜索结果
     */
    public JiraSearchResult getMyIssues(ToolContext toolContext) {
        String jql = JqlBuilder.getMyIssues();
        return searchIssues(jql, null, toolContext);
    }

    /**
     * 获取最近N天更新的Issues（支持ToolContext）
     *
     * @param days 天数
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 搜索结果
     */
    public JiraSearchResult getRecentIssues(int days, ToolContext toolContext) {
        String jql = JqlBuilder.getRecentIssues(days);
        return searchIssues(jql, null, toolContext);
    }

    /**
     * 获取项目的Issues
     *
     * @param projectKey 项目键值
     * @return 搜索结果
     */
    public JiraSearchResult getProjectIssues(String projectKey, ToolContext toolContext) {
        String jql = JqlBuilder.getProjectIssues(projectKey);
        return searchIssues(jql, null, toolContext);
    }

    /**
     * 获取项目中指定状态的Issues
     *
     * @param projectKey 项目键值
     * @param status 状态
     * @return 搜索结果
     */
    public JiraSearchResult getProjectIssuesByStatus(String projectKey, String status, ToolContext toolContext) {
        String jql = JqlBuilder.getProjectIssuesByStatus(projectKey, status);
        return searchIssues(jql, null, toolContext);
    }

    /**
     * 搜索包含指定文本的Issues（支持ToolContext）
     *
     * @param text 搜索文本
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 搜索结果
     */
    public JiraSearchResult searchByText(String text, ToolContext toolContext) {
        String jql = JqlBuilder.searchByText(text);
        return searchIssues(jql, null, toolContext);
    }

    /**
     * 获取Jira基础URL（用于构建链接）
     *
     * @return Jira基础URL
     */
    public String getApiBaseUrl() {
        return authService.getApiBaseUrl();
    }

    // 附件相关方法

    /**
     * 获取Issue的所有附件
     *
     * @param issueKey Issue键值
     * @return 附件列表
     */
    public List<JiraAttachment> getIssueAttachments(String issueKey, ToolContext toolContext) {
        logger.debug("Getting attachments for issue: {}", issueKey);

        try {
            // 获取Issue详情，包含附件信息
            JiraIssue issue = getIssue(issueKey, toolContext);
            List<Map<String, Object>> attachmentMaps = issue.getAttachments();

            if (attachmentMaps == null || attachmentMaps.isEmpty()) {
                return new ArrayList<>();
            }

            List<JiraAttachment> attachments = new ArrayList<>();
            for (Map<String, Object> attachmentMap : attachmentMaps) {
                JiraAttachment attachment = objectMapper.convertValue(attachmentMap, JiraAttachment.class);
                attachments.add(attachment);
            }

            logger.info("Successfully retrieved {} attachments for issue: {}", attachments.size(), issueKey);
            return attachments;

        } catch (Exception e) {
            logger.error("Failed to get attachments for issue: {}", issueKey, e);
            throw new JiraIntegrationException("Failed to get attachments for issue " + issueKey + ": " + e.getMessage(), e);
        }
    }

    /**
     * 获取单个附件的详细信息
     *
     * @param attachmentId 附件ID
     * @return 附件详情
     */
    public JiraAttachment getAttachment(String attachmentId, ToolContext toolContext) {
        logger.debug("Getting attachment: {}", attachmentId);

        String url = authService.getApiBaseUrl() + "/attachment/" + attachmentId;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<JiraAttachment> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, JiraAttachment.class);

            JiraAttachment attachment = response.getBody();
            logger.info("Successfully retrieved attachment: {}", attachmentId);
            return attachment;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Attachment not found: " + attachmentId);
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to attachment: " + attachmentId);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to get attachment: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error getting attachment: " + e.getMessage(), e);
        }
    }

    /**
     * 上传附件到Issue
     *
     * @param issueKey Issue键值
     * @param filePath 文件路径
     * @return 上传结果消息
     */
    public String uploadAttachment(String issueKey, String filePath, ToolContext toolContext) {
        logger.debug("Uploading attachment to issue: {} from file: {}", issueKey, filePath);

        String url = authService.getApiBaseUrl() + "/issue/" + issueKey + "/attachments";

        try {
            // 创建文件资源
            Resource fileResource = new FileSystemResource(filePath);
            if (!fileResource.exists()) {
                throw new JiraIntegrationException("File not found: " + filePath);
            }

            // 创建multipart请求
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileResource);

            // 设置请求头
            HttpHeaders headers = authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name());
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            headers.set("X-Atlassian-Token", "no-check"); // Jira要求的特殊头

            HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);

            String message = String.format("Successfully uploaded attachment %s to issue %s",
                                         fileResource.getFilename(), issueKey);
            logger.info(message);
            return message;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Issue not found: " + issueKey);
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to upload attachment to issue: " + issueKey);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            } else if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                throw JiraIntegrationException.apiCallFailed(
                    "Invalid file or attachment disabled: " + e.getResponseBodyAsString(), 400);
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to upload attachment: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error uploading attachment: " + e.getMessage(), e);
        }
    }

    /**
     * 删除附件
     *
     * @param attachmentId 附件ID
     * @return 删除结果消息
     */
    public String deleteAttachment(String attachmentId, ToolContext toolContext) {
        logger.debug("Deleting attachment: {}", attachmentId);

        String url = authService.getApiBaseUrl() + "/attachment/" + attachmentId;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.DELETE.name()));
            restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);

            String message = String.format("Successfully deleted attachment: %s", attachmentId);
            logger.info(message);
            return message;

        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw JiraIntegrationException.notFound("Attachment not found: " + attachmentId);
            } else if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
                throw JiraIntegrationException.accessDenied("Access denied to delete attachment: " + attachmentId);
            } else if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw JiraIntegrationException.authenticationFailed("Authentication failed");
            }
            throw JiraIntegrationException.apiCallFailed(
                "Failed to delete attachment: " + e.getMessage(), e.getStatusCode().value());
        } catch (ResourceAccessException e) {
            throw JiraIntegrationException.connectionFailed(
                "Connection failed to Jira server", e);
        } catch (Exception e) {
            throw new JiraIntegrationException("Unexpected error deleting attachment: " + e.getMessage(), e);
        }
    }
}
